/**
 * Created by wenpeng on 2016/12/12.
 */
$(function () {
    'use strict';
    ImporInfor();
    var supplyPhoto=[],     // 等待上传的图片
        meatCategory='/category/getMeatCategoryInfos?meatType=',   // 肉的种类
        providePlace="/country/getCountryInfos",                  // 获取产地
        urlProvide = '/myhome/purchaseInfo/addPurchaseInfo',     // 发布采购信息
        uuidLocal = Cookie.getCookie()['uuid'],                 //获取用户信息
        imgList = [],                                          // 图片上传数组
        $upInput = $('.uploadImg'),                           // 上传 input
        changeInput = false,                                 // input 值是否改变
        outWall = '/country/getCountryInfos',
        allCategoryApi = '/category/searchAllMeatCategory',
        categoryApi = '/ category/getMeatCategoryInfos',
        allPlaceApi = '/goodsLocus/searchAllGoodsLocus',
        numflag,
        default1 = function (obj) {
            if(obj.phone==undefined||obj.phone==""||obj.phone instanceof Object ){
                obj.phone=""
            }
            if(obj.username==undefined||obj.username==""||obj.username instanceof Object){
                obj.username=""
            }
            if(obj.wechat==undefined||obj.wechat==""||obj.wechat instanceof Object){
                obj.wechat=""
            }
            if(obj.qq==undefined||obj.qq==""||obj.qq instanceof Object){
                obj.qq=""
            }
            $("#supply-information .seller-information .name").val(obj.username);
            $("#supply-information .seller-information .phone").val(obj.phone);
            $("#supply-information .seller-information .QQ").val(obj.qq);
            $("#supply-information .seller-information .WeChat").val(obj.wechat);
        },                    // 列表
        unique = function (arr) {                           // 数组去重
            var n = [];
            for(var i = 0; i < arr.length; i++){
                if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
            }
            return n;
        }                      // 数组去重

    if(!uuidLocal){                                         // 没有登陆直接跳转
        layer.open({
            content: '您还没有登录，请先登录！'
            ,btn: ['去登录', '去首页']
            ,shadeClose:false
            ,yes: function(index){
                window.location.href = 'login.html';
                layer.close(index);
            }
            ,no: function (index) {
                window.location.href = 'index.html';
                layer.close(index);
            }
        });
        return;
    }                                   // 判断是否已登录

    // 日期遮罩层
    $('.laydate-icon').on('click', function () {
        $('#laydate_box').appendTo('.boxshow')
        $('.boxshow').show()
        $('body').addClass('over')
    })

    // 输入框键盘遮挡问题
    var jroll = new JRoll("#information",{
        scrollBarY: true,
        scrollBarFade: true
    });
    jroll.fixedinput(50); //使该JRoll对象里的input/textarea在focus时能自动上移到可见位置

// 默认卖方信息填充的数据
    ;(function () {

        // 用户信息
        $.ajax({
            url:host + '/myhome/account/getAccountInfo',
            type:'post',
            data:Infornation,
            success:function(res){
                if(res.success == true){
                    //生成数据时页面清空
                    var data = res.data;
                    default1(res.data)
                }else{
                    //就是无数据则返回什么
                    lay.msg('获取用户信息失败，请手动输入个人信息')
                    default1({})
                }
            },
            error:function () {
                lay.msg('获取用户信息失败，请手动输入个人信息')
                default1({})
            }
        });

    })();

// label 变色
    $('label').click(function () {
        $(this).siblings('label').css('color', '#999999')
        $(this).css('color','#1a1a1a')
    })

// 初始化产品类别

    $('input[name="meat-type-input"]').on('click', function () {
        $('.meat-category-input').val('')
        $('.meat-category-input').data('value', '')
        $('.meat-type-input').data('value',$(this).val())
        getSupplyMeatCategoryInfos($(this).val());
    })

//初始化供应类型
    $('input[name="supply-type-input"]').on('click', function () {
        $('.supply-type-input').data('value',$(this).val());
    })

//初始化包装规格
    $('input[name="supply-packing-input"]').on('click', function () {
        $('.supply-packing-input').data('value',$(this).val());
    })

// 取消按钮

    $('#cancle').on('click', function () {
        layer.open({
            content: '确认取消操作吗？您的信息可能不会保存！'
            ,btn: ['取消', '确定']
            ,style: 'color:#333;'
            ,skin: 'footer'
            ,no: function(){
                layer.closeAll();
                window.location.href = 'index.html'
            }
        });
    })


//供应展开收起的按钮
    $('#information .zhaoniu-panel-title').click(function(){
        var cuttent = $(this).parent('.row').next('div.is-show');
        cuttent.toggleClass('hidden')
        $(this).find('div').toggleClass('upDown')
        jroll.refresh();
    });

// // 模块框 取消
//     $(".modal>.modal-dialog>.modal-content>.cancel").click(function(){
//         $('.supply-meat-category').modal('hide');
//         $('.supply-place').modal('hide');
//     });


//上传图片

    $('#supply-upload-photo').on('change', function () {
        changeInput = true;
        var files;
        if (!this.files.length) return;
        files = Array.prototype.slice.call(this.files);
        if(files.length + imgList.length > 5){
            lay.msg('最多可以同时上传五张照片')
            return;
        }
        if(files.length + imgList.length === 5){
            $upInput.hide();
        }else{
            $upInput.show();
        }
        lay.msg('正在进行图片压缩')
        files.forEach(function (file) {
            lrz(file,{
                quality: 0.5,
                fieldName: 'imageFile',
                width: 880
            })
                .then(function (rst) {
                    // 处理成功会执行
                    console.log(rst)
                    imgList.push(rst)
                    $('<span><i data-img='+(imgList.length-1)+'></i><div><img src="'+rst.base64+'" alt=""></div></span>').insertBefore('.uploadImg');
                    $('.img-container span').css('height',$('.img-container span').width());
                })
                .catch(function (err) {
                    // 处理失败会执行
                    console.log(err)
                    lay.msg('压缩图片失败，请刷新后重试')
                })
                .always(function () {
                    // 不管是成功失败，都会执行
                });
        })
        // console.log(imgList)
    })
    $('.img-container').on('click', function (e) {
        var target = e.target,
            imgUrl = e.target.src?e.target.src:'',
            count;
        if (target.nodeName==="IMG") {
            $('#imgbox').empty().append('<div><i></i><img src='+imgUrl+'></div>').show()
        }else if(target.nodeName==="I"){
            layer.open({
                content: '确认删除照片吗？'
                ,btn: ['取消', '确定']
                ,style: 'color:#333;'
                ,skin: 'footer'
                ,no: function(){
                    layer.closeAll();
                    count = $(target).data('img');
                    imgList.splice(count,1)
                    supplyPhoto.splice(count,1)
                    $(target).parent('span').fadeOut(500,function () {
                        if(imgList.length < 5) {
                            $upInput.show();
                        }
                        $(this).remove()
                        $('.img-container').find('i').each(function () {
                            $(this).attr('data-img',$(this).index('i'))
                        })
                    })
                }
            });


        }
    })
    $('#imgbox').click(function () {
        $(this).hide();
    })
// 图片上传
    function upLoadImg() {

        if(changeInput){
            supplyPhoto = [];
            var index = 0
            imgList.forEach(function (rst,num) {
                $.ajax({
                    url:hostImgUpload,
                    type:"post",
                    data:rst.formData,
                    processData:false,// 不要处理发送的数据
                    contentType:false,// 不要设置请求头
                    dataType:'json',
                    beforeSend:function () {
                        layer.open({
                            type: 2
                            ,content: '图片上传中...'
                            ,shadeClose:false
                        });
                    },
                    success:function(data){
                        changeInput = false;
                        index++;
                        supplyPhoto.push(data.message)
                        if(index === imgList.length){
                            layer.closeAll();
                            var supplyInfoTxt =  $(".content").val();
                            $(".provide-info-input").val(supplyInfoTxt);
                            $(".provide-info-input").data("image",supplyPhoto);
                            lay.msg('图片上传完毕，祝您工作愉快')
                            addProvideInfo()
                        }
                    },
                    error:function(e){
                        alert("错误！！");
                        // window.clearInterval(timer);
                    }
                });
            })
        }else {
            var supplyInfoTxt =  $(".content").val();

            $(".provide-info-input ").val(supplyInfoTxt);
            $(".provide-info-input ").data("image",supplyPhoto);
        }
    }


// 发布
    $('#true button').on('click', function () {
        if(changeInput){
            upLoadImg();
        }else{
            addProvideInfo()
        }

    })

    function addProvideInfo(){

        var parm="";
        //获取产品的种类
        var meatTypeInput =$("#information .meat-type-input").data("value") || '0';
        //获取产品的类别
        var meatCategoryInput =$("#information .meat-category-input").data("value");
        //获取供应类型
        var supplyTypeInput =$("#information .supply-type-input").data("value");


        //获取产品详情
        var provideInfoInput =$("#information .content").val();
        //获取产品图片
        var provideImage =$("#information .provide-info-input").data("image");

        //获取肉数量
        var meatNumInput =$("#information .meat-num-input").val();
        //获取肉单位
        var meatunitInput =$("#information .meat-unit-input").val();
        //获取单价
        var meatPriceInput =$("#information .meat-price-input").val();
        //获取产地
        var supplyPlaceInput =$("#information .supply-place-input").data("value");
        //获取货源地
        var goodsPlaceInput = $('#information .goods-place-input').val();
        //获取厂号
        var factoryNumInput =$("#information .factory-num-input").val();
        //获取包装规格
        var supplyPackingInput =$("#information .supply-packing-input").data("value");
        //获取精修比例
        var scaleInput =$("#information .scale-input").val();
        //企业名称
        var enterpriseInput = $('#information .enterprise-input').val();
        //获取保质期
        var qualityGuaranteePeriod =$("#information .quality-guarantee-period").val();
        //获取失效期
        var failurePeriodInput =$("#information .failure-period-input").val();
        //获取姓名
        var name =$("#information .name").val();
        //获取手机号
        var phone =$("#information .phone").val();
        //获取QQ
        var QQ =$("#information .QQ").val();
        //获取微信
        var weChat =$("#information .WeChat").val();



        if(meatTypeInput=="undefined"||meatTypeInput==null||meatTypeInput===""){
            layer.closeAll();
            lay.msg("产品种类不可以为空");
            return;
        }else{
            parm = parm + "&meatType=" + meatTypeInput;
        }



        if(provideInfoInput=="undefined"||provideInfoInput==null||provideInfoInput===""){
            layer.closeAll();
            lay.msg("产品详情不可以为空");
            return;
        }else {
            parm = parm + "&purchaseDesc=" + encodeURIComponent(provideInfoInput);
        }

        if(meatCategoryInput!="undefined"&&meatCategoryInput!=""&&meatCategoryInput!=null) {
            parm = parm + "&meatCategoryId=" + meatCategoryInput;
        }


        if(meatNumInput!="undefined"&&meatNumInput!=""&&meatNumInput!=null) {
            parm = parm + "&amount=" + meatNumInput;
        }


        if(meatunitInput!="undefined"&&meatunitInput!=""&&meatunitInput!=null) {
            parm = parm + "&unit=" + meatunitInput;
        }


        if(meatPriceInput!="undefined"&&meatPriceInput!=""&&meatPriceInput!=null) {
            parm = parm + "&price=" + meatPriceInput;
        }


        if(supplyPlaceInput!="undefined"&&supplyPlaceInput!=""&&supplyPlaceInput!=null) {
            parm = parm + "&countryId=" + supplyPlaceInput;
        }

        if(goodsPlaceInput != '不限' &&goodsPlaceInput!="undefined"&&goodsPlaceInput!=""&&goodsPlaceInput!=null) {
            parm = parm + "&deliveryArea=" + goodsPlaceInput;
        }


        if(supplyPackingInput!="undefined"&&supplyPackingInput!=""&&supplyPackingInput!=null) {
            parm = parm + "&packingId=" + supplyPackingInput;
        }


        if(supplyTypeInput!="undefined"&&supplyTypeInput!=""&&supplyTypeInput!=null) {
            parm = parm + "&provideWayId=" + supplyTypeInput;
        }

        if(qualityGuaranteePeriod!="undefined"&&qualityGuaranteePeriod!=""&&qualityGuaranteePeriod!=null) {
            parm = parm + "&shelfLife=" + qualityGuaranteePeriod;
        }

        if(scaleInput!="undefined"&&scaleInput!=""&&scaleInput!=null) {
            parm = parm + "&scale=" + scaleInput;
        }
        if(enterpriseInput!="undefined"&&enterpriseInput!=""&&enterpriseInput!=null) {
            parm = parm + "&enterprise=" + enterpriseInput;
        }

        if(factoryNumInput!="undefined"&&factoryNumInput!=""&&factoryNumInput!=null) {
            parm = parm + "&factoryNo=" + factoryNumInput;
        }

        if(failurePeriodInput!="undefined"&&failurePeriodInput!=""&&failurePeriodInput!=null) {
            parm = parm + "&invalidDate=" + failurePeriodInput;
        }

        if(name!="undefined"&&name!=""&&name!=null) {
            parm = parm + "&contact=" + name;
        }

        if(phone!="undefined"&&phone!=""&&phone!=null) {
            parm = parm + "&phone=" + phone;
        }

        if(QQ!="undefined"&&QQ!=""&&QQ!=null) {
            parm = parm + "&qq=" + QQ;
        }

        if(weChat!="undefined"&&weChat!=""&&weChat!=null) {
            parm = parm + "&weChat=" + weChat;
        }
        parm=parm +"&" + Infornation;
        layer.open({
            type: 2
            ,content: '正在发布...'
            // ,shadeClose:false
        });
        $.ajax({
            url:host + urlProvide,
            data:parm,
            type:"get",
            success:function(res){
                layer.closeAll();
                if(res.success == true){
                    self.location="message.html?purchase=true";
                }else{
                    lay.msg(res.message)
                }
            },
            error:function () {
                return null;
            }
        });
    };
    // 产品类别
    $('.row').eq(2).on('click', function () {
        var num = Number($("#information .meat-type-input").data("value") || '0');
        $('.leibie-box').removeClass('hidden').animate({"width": "100%"},100);
        if(numflag === num){
            return
        }
        $.getJSON(host + allCategoryApi, function (data) {
            var htmlStr = '<ul class="searchItim"><li data-id="0" class="check"><a href="javascript:;">不限</a> </li>',
                contentBox = $('.item-leibie').eq(0),
                parseData = function (data) {
                    var data = data.childrenList?data.childrenList:data;
                    for(var i = 0; i < data.length; i++){
                        if(data[i].childrenList.length){
                            htmlStr += '<li><a href="javascript:;">'+data[i].meatName+'</a> <ul style="display: none;">'
                            parseData(data[i].childrenList)
                            htmlStr += '</ul></li>'
                        }else {
                            htmlStr += '<li data-id='+data[i].id+' class="check"><a href="#">'+data[i].meatName+'</a></li>'
                        }
                    }
                }
            if (data.success) {
                numflag = num;
                $('.searchItim').remove();
                parseData(data.data[num])
                htmlStr += '</ul>'
                contentBox.append(htmlStr)

                // 手风琴效果
                $('.searchItim', contentBox).accordion({
                    //accordion: true,
                    speed: 100,
                    closedSign: '[+]',
                    openedSign: '[-]'
                })
                // 点击事件
                $('.check', contentBox).on('touchstart', function () {
                    $(this).find('a').css('backgroundColor','#eee')
                })
                $('.check', contentBox).on('touchend', function () {
                    $(this).find('a').css('backgroundColor','transparent')
                })
                $('.check', contentBox).on('click', function () {
                    $('.check', contentBox).removeClass('checked');
                    $(this).addClass('checked')
                    $('.icon-search input[name="leibie"]').val($(this).text())
                    $("#information .meat-category-input").val($(this).text());
                    $("#information .meat-category-input").data("value",$(this).data('id'))
                    $('.leibie-box').animate({"width": "0px"},100,function () {
                        $(this).addClass('hidden')
                    });
                })

            } else {
                lay.msg('获取产品类别失败，请刷新后重试')
            }
        });
    })
    // 模糊搜索
    $('.icon-search input').on('input', function () {
        var val = $(this).val().trim(),
            _this = $(this);
        if(val){
            $.getJSON(host+categoryApi,{keyWord:val}, function (data) {
                if(data.success){
                    var numData = data.data,htmlStr = '';
                    $.each(numData, function () {
                        htmlStr += '<li data-id='+this.id+'>'+this.meatName+'</li>'
                    })
                    _this.siblings('.searchResult').find('button').on('click',function () {
                        $('.icon-search input').val('')
                        $(this).parent('div.searchResult').addClass('hidden')
                    })
                    _this.siblings('.searchResult').removeClass('hidden').find('ul').html(htmlStr)
                        .on('click',function (e) {
                            var $this = $(this),
                                $target = $(e.target);
                            if(e.target.nodeName === 'LI'){
                                $('.check').removeClass('checked')
                                $('.icon-search input').val($target.text())
                                $this.empty().parent('div.searchResult').addClass('hidden');
                                $("#supply-information>.fill-information .row .meat-category-input").val($target.text());
                                $("#supply-information>.fill-information .row .meat-category-input").data("value", $target.data('id'));
                                $('.leibie-box').animate({"width": "0"},100,function () {
                                    $(this).addClass('hidden');
                                })
                            }
                        })

                }else {
                    console.log(data.message)
                }
            })
        }else {
            _this.siblings('.searchResult').addClass('hidden')
        }
    })
    // 产品类别 关闭
    $('.leib-l').on('click', function () {
        $('.leibie-box').animate({"width": "0"},100,function () {
            $(this).addClass('hidden');
        })
    })
    // 产品类别 按钮关闭
    $('.icon-search span').on('click', function () {
        $('.leibie-box').animate({"width": "0"},100,function () {
            $(this).addClass('hidden');
        })
    })
    //产地
    $('.row').eq(7).on('click', function () {
        if($('.searchItim', '.item-chandi')[0]){
            $('.item-chandi').removeClass('hidden')
            return
        }
        $.getJSON(host + outWall, function (data) {
            var htmlStr = '<ul class="searchItim"><li class="check" data-id="0"><a href="javascript:;">不限</a> </li>',
                contentBox = $('.item-chandi .content1'),
                parseData = function (data) {
                    var inWallLi = '<li><a href="javascript:;">国内</a><ul style="display: none;">',
                        outWallLi = '<li><a href="javascript:;">国外</a><ul style="display: none;">';
                    for(var i = 2;i < data.length; i++){
                        var str = '<li class="check" data-id='+data[i].id+' ><a href="javascript:;">'+data[i].countryName+'</a></li>'
                        if(data[i].parentId === 1){
                            inWallLi += str;
                        }else {
                            outWallLi += str;
                        }

                    }
                    inWallLi += '</ul>';
                    outWallLi += '</ul>';
                    htmlStr += inWallLi + outWallLi;
                }
            if (data.success) {
                $('.item-chandi').removeClass('hidden')
                parseData(data.data)
                htmlStr += '</ul>'
                contentBox.append(htmlStr)

                // // 手风琴效果
                $('.searchItim', contentBox).accordion({
                    //accordion: true,
                    speed: 100,
                    closedSign: '[+]',
                    openedSign: '[-]'
                })
                // 点击事件
                $('.check', contentBox).on('touchstart', function () {
                    $(this).find('a').css('backgroundColor','#eee')
                })
                $('.check', contentBox).on('touchend', function () {
                    $(this).find('a').css('backgroundColor','transparent')
                })
                $('.check', contentBox).on('click', function () {
                    $('.check', contentBox).removeClass('checked');
                    $(this).addClass('checked')
                    $(this).find('a').css('backgroundColor','transparent')
                    $("#information .supply-place-input").val($(this).text());
                    $("#information .supply-place-input").data("value",$(this).data('id'));
                    $('.item-chandi').addClass('hidden')
                })
            } else {
                console.log(data.message)
            }
        })
    })
    // 产地取消按钮
    $('.content1 button').on('click', function () {
        $('.item-chandi').addClass('hidden')
    })

    // 交货地地
    $('.row').eq(8).find('.col-xs-1').on('click', function () {
        if($('.searchItim', '.item-warehouse')[0]){
            $('.item-warehouse').removeClass('hidden')
            return
        }
        // 所在地
        $.getJSON(host + allPlaceApi, function (data) {
            var htmlStr = '<ul class="searchItim"><li class="check" data-id="0"><a href="javascript:;">不限</a> </li>',
                contentBox = $('.item-warehouse .content1'),
                parseData = function (data) {
                    for(var i = 0; i < data.length; i++){
                        if(data[i].childrenList.length){
                            htmlStr += '<li><a href="javascript:;">'+data[i].goodsLocusName+'</a> <ul style="display: none;">'
                            parseData(data[i].childrenList)
                            htmlStr += '</ul></li>'
                        }else {
                            htmlStr += '<li data-id='+data[i].id+' class="check"><a href="#">'+data[i].goodsLocusName+'</a></li>'
                        }
                    }
                };
            if (data.success) {
                $('.item-warehouse').removeClass('hidden')
                parseData(data.data)
                htmlStr += '</ul>'
                contentBox.append(htmlStr)

                // // 手风琴效果
                $('.searchItim', contentBox).accordion({
                    //accordion: true,
                    speed: 100,
                    closedSign: '[+]',
                    openedSign: '[-]'
                })
                // 点击事件
                $('.check', contentBox).on('touchstart', function () {
                    $(this).find('a').css('backgroundColor','#eee')
                })
                $('.check', contentBox).on('touchend', function () {
                    $(this).find('a').css('backgroundColor','transparent')
                })
                $('.check', contentBox).on('click', function () {
                    $('.check', contentBox).removeClass('checked');
                    $(this).addClass('checked')
                    $(this).find('a').css('backgroundColor','transparent')
                    $("#information .goods-place-input").val($(this).text());
                    $('.item-warehouse').addClass('hidden')
                })
            } else {
                console.log(data.message)
            }
        })
    })
    // 交货地取消按钮
    $('.item-warehouse button').on('click', function () {
        $('.item-warehouse').addClass('hidden')
    })
    // 发布数据限制
    $('input.limit').on('blur', function () {
        var name = $(this).attr('name'),
            value = $(this).val().trim();
        console.log(name+'----'+value)
        if(!value) {return false};
        if(name == 'meatNumInput'){
            if(value < 0 || value > 999999999){
                $(this).css('border','1px solid red')
                lay.msg("数量超出限制")
            }else {
                $(this).removeAttr('style')
            }
        }else if(name == 'meatPriceInput'){
            if(value < 5000 || value > 999999){
                $(this).css('border','1px solid red')
                lay.msg("价格超出限制")
            }else {
                $(this).removeAttr('style')
            }
        }
    })
})

